<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据查询</title>
    <style>
        body {
            background-color: #333;
            color: #fff;
        }
		.centered {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
		}
		.led_on{
			color:white;
			background-color: green;
		}
		.led_off{
			color:white;
			background-color: red;
		}
		table {
			border-collapse: collapse;
			width: 80%;
			margin: 0 auto;
			margin-top: 40px;
		}
		th, td {
			border: 1px solid #ccc;
			padding: 8px;
			text-align: center;
		}
		th {
			background-color: #333;
		}
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
	<script src="https://cdn.bootcdn.net/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
</head>
<body>
    <div class="centered">
        <label for="startTime">开始时间：</label>&nbsp
        <input type="datetime-local" id="startTime">&nbsp &nbsp
        <label for="endTime">结束时间：</label>&nbsp
        <input type="datetime-local" id="endTime">&nbsp &nbsp
		<input type="checkbox" id="autoRefresh" checked>自动刷新(2s)</input>&nbsp  &nbsp
		<button id="queryBtn">立即刷新</button>&nbsp  &nbsp
		<button id="ledBtn">LED</button>
    </div>
    <table id="resultTable">
        <thead>
            <tr>
                <th>序号</th>
                <th>温度（℃）</th>
                <th>气压（Bar）</th>
				<th>海拔（米）</th>
                <th>电压（v）</th>
                <th>位置</th>
                <th>行程开关</th>
                <th>时间</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
     <script>
        $(document).ready(function() {
            var token = getCookie("token");
            if (!token) {
                window.location.href = "/login";
            }
            $("#queryBtn").click(queryData);
			$("#ledBtn").click(setLedState);
			//使用定时器刷新
			var interval_id = setInterval(queryData, 2000);
			$("#autoRefresh").click(function(){
				if ($("#autoRefresh").is(':checked')){
					interval_id = window.setInterval(queryData, 2000);
				}else{
					window.clearInterval(interval_id)
				}
			})

			//初始化时刷新
			queryData();
        });

        function getCookie(name) {
			//获取cookie的内容
            var value = "; " + document.cookie;
            var parts = value.split("; " + name + "=");
            if (parts.length == 2) return parts.pop().split(";").shift();
        }
		
		function setLedState(){
			//设置led状态
			var btn = $("#ledBtn"); //拿到led按钮
			var led_state = ! btn.hasClass("led_on"); //获取当前状态，并取反
			var token = getCookie("token"); //获取token
			var data = {'state': led_state} //构造提交的数据
			//发起请求
			$.ajax({
				url: "/mgr/setled",
				type: "POST",
				contentType: "application/json",
				data: JSON.stringify(data),
				headers: {
					"token": token
				},
				success: function(response) {
					if (response.code === 0) {
						//更新按钮状态
						update_ledButton(led_state);
					} else if (response.code === 340) {
						window.location.href = "/login";
					} else {
						alert(response.msg);
					}
				},
				error: function() {
					alert("请求失败，请稍后重试");
				}
			});
				
		}
		function queryData(){
			//查询数据和led状态
			var startTime = $("#startTime").val();
			if (startTime && startTime.length>6){
				startTime = moment(startTime).format("YYYY-MM-DD HH:mm:ss");
			}
			var endTime = $("#endTime").val();
			if (endTime && endTime.length>6){
				endTime = moment(endTime).format("YYYY-MM-DD HH:mm:ss");
			}
			var data = {
				'from': startTime,
				'to': endTime
			};
			var token = getCookie("token");
			$.ajax({
				url: "/mgr/getdata",
				type: "POST",
				contentType: "application/json",
				data: JSON.stringify(data),
				headers: {
					"token": token
				},
				success: function(response) {
					if (response.code === 0) {
						displayData(response.data);
						update_ledButton(response.led_state);
					} else if (response.code === 340) {
						window.location.href = "/login";
					} else {
						alert(response.msg);
					}
				},
				error: function() {
					alert("请求失败，请稍后重试");
				}
			});
		}
		
		function update_ledButton(state){
			//更新led按钮状态
			var btn = $("#ledBtn");
			if (state){
				btn.removeClass("led_off")
				btn.addClass("led_on")
			}else{
				btn.removeClass("led_on")
				btn.addClass("led_off")
			}
		}
        function displayData(data) {
			//更新表格数据
            var tableBody = $("#resultTable tbody");
            tableBody.empty();
            data.forEach(function(item, index) {
                var row = $("<tr></tr>");
                row.append($("<td></td>").text(index + 1));
                row.append($("<td></td>").text(item.temperature));
                row.append($("<td></td>").text(item.pressure));
				row.append($("<td></td>").text(item.altitude));
                row.append($("<td></td>").text(item.voltage));
                row.append($("<td></td>").text(item.position));
                row.append($("<td></td>").text(item.switch ? "开" : "关"));
                row.append($("<td></td>").text(item.time));
                tableBody.append(row);
            });
        }
    </script>
</body>
</html>
